<?php declare(strict_types=1);

namespace Zyucv7\Core\Database\Driver;

use PDO;
use Zyucv7\Core\Database\Driver AS DatabaseDriver;
use Zyucv7\Core\Database\DatabaseException;

class Mysql extends DatabaseDriver
{

    /**
     * 构造函数
     * @param string $host 数据库主机
     * @param string $dbname 数据库名
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $charset 字符集，默认utf8mb4
     * @throws PDOException
     */
    public function __construct($config)
    {
        $this->config = $config;
        $this->connect();
    }

    private function connect(): void
    {
        $host = $this->config['host'] ?? '127.0.0.1';
        $dbname = $this->config['database'] ?? '';
        $charset = $this->config['charset'] ?? 'utf8mb4';
        if (empty($dbname)) {
            throw DatabaseException::InvalidArgument("Database name is required.");
        }
        $dsn = "mysql:host={$host};dbname={$dbname};charset={$charset}";
        
        try {
            $this->pdo = new PDO($dsn, $this->config['username'], $this->config['password'], $this->options);
        } catch (\PDOException $e) {
            throw DatabaseException::Pdo($e->getMessage());
        }
    }
    
}
